<template>
  <div class="search">
    <div class="searchTop">
      <div class="searchTopbark" @click="$router.go(-1)">
        <img
          v-if="value === ''"
          src="../assets/image/ic_back_dark_center.png"
          alt=""
        />
        <span v-else></span>
      </div>
      <input
        class="searchTopinp"
        type="text"
        v-model="value"
        placeholder="请输入食物名字"
        @keydown.enter="showlist(value)"
      />
      <div class="searchTopdele">
        <span
          @click.stop="$router.push({ path: '/dlzong' })"
          v-if="value === ''"
          ><img src="../assets/image/ic_scan_main.png" alt=""
        /></span>
        <span @click="value = ''" v-else
          ><img src="../assets/image/ic_analyze_cancel.png" alt=""
        /></span>
      </div>
      <div class="searchTopdianjisous" @click="showlist(value)">
        <img src="../assets/image/ic_homepage_search.png" alt="" />
      </div>
    </div>

    <!-- 历史记录 -->
    <div class="searchTodolist" v-if="showfalg && todolist.length !== 0">
      <div class="searchTodolisttitle">最近搜过</div>
      <ul>
        <TodoItem
          v-for="todo in todolist"
          :key="todo.id"
          :todo="todo"
          @update:todo="
            showlist($event);
            value = $event;
          "
        />
      </ul>
      <div class="cleartodo" @click="cleartodolist">
        <span><img src="../assets/image/ic_trash_normal.png" alt="" /></span>
        <span>清空历史记录</span>
      </div>
    </div>

    <!-- 大家都在搜 -->
    <div class="searchmore" v-if="showfalg">
      <div class="searchmoretitle">大家都在搜</div>
      <ul>
        <li v-for="item in keywordslist" :key="item" @click="showlist(item)">
          {{ item }}
        </li>
      </ul>
    </div>

    <div v-if="!showfalg">
      <van-cell @click.stop="shows = true">
        <div class="neixunakan">
          <div>
            <span>{{ yingsupailist }}</span>
          </div>

          <div
            v-if="yingsupailist !== '营养素排序'"
            @click.stop="heilod = !heilod"
          >
            <span v-if="heilod"><van-icon name="ascending" />由高到低</span>
            <span v-else><van-icon name="descending" />由低到高</span>
          </div>

          <div v-else @click.stop="tuijian">
            <van-checkbox v-model="checked" checked-color="#ee0a24"
              >推荐食品</van-checkbox
            >
          </div>
        </div>
      </van-cell>
      <van-popup v-model="shows" position="bottom" :style="{ height: '30%' }">
        <ul class="compositionxiala">
          <CompositionItem
            v-for="item in compositionlist"
            :key="item.id"
            :item="item"
            @click.native="showlog(item)"
          />
        </ul>
      </van-popup>

      <ul v-if="foodslist.length !== 0 && landing">
        <FoodItem
          v-for="(items, index) in foodslist"
          :key="index"
          :items="items"
        />
      </ul>
      <ul v-else>
        <li v-for="(items, index) in foodslist" :key="index">
          <van-skeleton title :row="2" />
        </li>
      </ul>
    </div>

    <div class="alearxianshi" v-if="falg">
      <span>输入框不能为空</span>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

import TodoItem from "@/components/TodoItem.vue";
import FoodItem from "@/components/FoodItem.vue";
import CompositionItem from "@/components/CompositionItem.vue";

export default {
  components: {
    TodoItem,
    FoodItem,
    CompositionItem,
  },
  computed: {
    ...mapState(["foodbank"]),
  },
  data() {
    return {
      value: "",
      //大家都在搜
      keywordslist: [],
      //历史记录
      todolist: [],
      //搜索到的内容
      foodslist: [],
      compositionlist: [],
      shows: false,
      yingsupailist: "营养素排序",
      yingsupailistindex: 0,
      showfalg: true,
      //推荐食品
      checked: false,
      heilod: true,
      newcode: null,
      falg: false,
      landing: false,
    };
  },
  //创建
  created() {
    this.axios.get("https://food.boohee.com/fb/v1/keywords").then((res) => {
      this.keywordslist = res.data.keywords;
    });

    this.axios
      .get(
        `https://food.boohee.com/fb/v1/foods/sort_types?User-Agent=food%2Fandroid`
      )
      .then((res) => (this.compositionlist = res.data.types));

    //本地存储
    if (window.localStorage.getItem("todolists") === null) {
      //   console.log("等于空");
    } else {
      this.todolist = JSON.parse(window.localStorage.getItem("todolists"));
    }
  },
  //方法
  methods: {
    showlist(v) {
      if (v === "") {
        this.falg = true;
        setTimeout(() => {
          this.falg = false;
        }, 1000);
        return;
      }
      //赋值到input框
      this.value = v;
      //清除foodslist的数据
      this.foodslist = [];
      this.showfalg = false;

      //插入
      let max = Math.max(...this.todolist.map((item) => item.id));
      if (max == -Infinity) {
        max = 0;
      }
      this.todolist.push({
        id: max + 1,
        text: v,
      });
      //数组去重
      let arr = Array.from(new Set(this.todolist.map((item) => item.text)));
      this.todolist = arr.map((res, index) => {
        if (res !== undefined) {
          return { id: index + 1, text: res };
        }
      });
      //本地存储
      window.localStorage.setItem("todolists", JSON.stringify(this.todolist));

      this.axios
        .get(`https://food.boohee.com/fb/v1/search?order_asc=desc&q=${v}`)
        .then((res) => {
          this.foodslist = res.data.items;
          setTimeout(() => {
            this.landing = true;
          }, 1000);
        });
    },
    //清除本地储存
    cleartodolist() {
      this.todolist = [];
      window.localStorage.setItem("todolists", JSON.stringify(this.todolist));
    },
    showlog(v) {
      this.yingsupailist = v.name;
      this.shows = false;
      this.yingsupailistindex = v.index;
      this.newcode = v.code;
      this.axios
        .get(
          `https://food.boohee.com/fb/v1/search?q=${this.value}&order_by=${v.code}`
        )
        .then((res) => (this.foodslist = res.data.items));
    },
    menu() {
      this.scroll =
        document.documentElement.scrollTop || document.body.scrollTop;
    },
    tuijian() {
      // console.log(this.checked);
      if (this.checked !== true) {
        this.axios
          .get(
            `https://food.boohee.com/fb/v1/search?order_asc=desc&q=${this.value}&health_light=1`
          )
          .then((res) => (this.foodslist = res.data.items));
        // &health_light=1
      } else {
        this.axios
          .get(
            `https://food.boohee.com/fb/v1/search?order_asc=desc&q=${this.value}`
          )
          .then((res) => (this.foodslist = res.data.items));
      }
    },
  },
  watch: {
    value(n) {
      if (n === "") {
        this.showfalg = true;
      }
    },
    heilod(n) {
      if (n === true) {
        this.axios
          .get(
            `https://food.boohee.com/fb/v1/search?order_asc=desc&q=${this.value}&order_asc=desc&order_by=${this.newcode}`
          )
          .then((res) => (this.foodslist = res.data.items));
      } else {
        this.axios
          .get(
            `https://food.boohee.com/fb/v1/search?order_asc=desc&q=${this.value}&order_asc=asc&order_by=${this.newcode}`
          )
          .then((res) => (this.foodslist = res.data.items));
      }
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  width: 100%;
  //value为空时弹出
  position: relative;
  .alearxianshi {
    position: absolute;
    // bottom: 10px;
    background: #c1cdcd;
    border-radius: 10px;
    bottom: 10%;
    left: 50%;
    transform: translateX(-50%) scale(1.2);
    text-align: center;
    span {
      // color: white;
      padding: 20px 10px;
      // border: 10px solid red;
    }
  }

  .searchTop {
    width: 100%;
    display: flex;
    align-items: center;
    position: relative;
    padding: 10px 5px;
    .searchTopbark {
      width: 10%;
      height: 100%;
      img {
        width: 100%;
        vertical-align: middle;
      }
    }
    .searchTopinp {
      flex: 1;
      background: #f6f6f6;
      padding: 5px;
      border: 0;
    }
    .searchTopdele {
      position: absolute;
      width: 10%;
      right: 10%;
      top: 12px;
      span {
        img {
          width: 85%;
          vertical-align: middle;
        }
      }
    }
    .searchTopdianjisous {
      width: 10%;
      img {
        width: 100%;
        vertical-align: middle;
      }
    }
  }
  .searchTodolist {
    width: 100%;
    border: 1px solid gray;
    border-left: 0;
    border-right: 0;
    .searchTodolisttitle {
      width: 100%;
      padding: 8px 10px;
      background: #f6f6f6;
      color: gray;
    }
    ul {
      width: 100%;
      li {
        width: 100%;
      }
    }
    .cleartodo {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      span {
        margin-bottom: 10px;
        &:nth-child(1) {
          display: flex;
          justify-content: center;
          align-items: center;
          img {
            width: 55%;
            vertical-align: middle;
          }
        }
        &:nth-child(2) {
          color: gray;
        }
      }
    }
  }
  .searchmore {
    width: 100%;
    .searchmoretitle {
      width: 100%;
      padding: 10px 10px;
      color: gray;
      background: #f6f6f6;
      border-bottom: 1px solid gray;
    }

    ul {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      li {
        flex-basis: 50%;
        width: 100%;
        padding: 15px 10px;
        border-bottom: 1px solid gray;
      }
    }
  }
  .neixunakan {
    display: flex;
    justify-content: space-between;
  }

  .compositionxiala {
    width: 100%;
    position: absolute;
    background: white;
    overflow: hidden;
    overflow-y: auto;
    padding: 0 10px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    li {
      list-style: none;
      flex-basis: 33%;
      // border-bottom: 1px solid rgba(128, 128, 128, 0.5);
      padding: 15px;
      text-align: center;
    }
  }
}
</style>